/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package executing;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ryuju
 */
public class TempBuildDirectory {
    private static final Logger log = Logger.getLogger(TempBuildDirectory.class.getName());
    public static final String PREFIX = TempBuildDirectory.class.getSimpleName();

    private File directory;     
    boolean isDispose = false;
    public TempBuildDirectory() {     
        create();
    }        
    
    public String getAbsolutePath()
    {
        if(null != directory)
        {
            return directory.getAbsolutePath();
        }
        return null;
    }
    
    
    private void create() {    

        if (directory == null) {              
            directory = nonExistingTempDir();     
        }      

        if (directory.exists()) {             
            throw new IllegalArgumentException("Already exists: " + directory);      
        }          
        if (!directory.mkdir()) {              
            throw new RuntimeException("Unable to create directory: " + directory);
        }     
    }       
    private static File nonExistingTempDir() {         
        int i = 0;         
        File dir;          
        do {              
            i++; 
            dir = new File(System.getProperty("java.io.tmpdir"), PREFIX + i);
        } while (dir.exists());
        return dir;     
    }       
    public void dispose() 
    {    
        if(!isDispose)
        {
            isDispose = true;
            deleteRecursively(directory);   
        }
    }      
    private static void deleteRecursively(File file)
    {       
        if (file.isDirectory())
        {        
            for (File contained : file.listFiles())
            {               
                deleteRecursively(contained);  
            }     
        }       
        if (!file.delete())
        {           
            log.log(Level.WARNING, "Unable to delete file: {0}", file);  
            anotherDeleteAttempt(file);      
        }   
    }      
    private static void anotherDeleteAttempt(File file)
    {    
        try {   
            Thread.sleep(1000);   
        } catch (InterruptedException e) { 
        }        
        file.delete();    
        file.deleteOnExit();    
        if (!file.exists()) {   
            log.log(Level.INFO, "File was deleted on a second try: {0}", file);  
        }  
    } 
}
